package com.xzx.mr.reducer;

import com.xzx.mr.kv.AnalysisKey;
import com.xzx.mr.kv.AnalysisValue;
import lombok.extern.slf4j.Slf4j;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;
import java.util.Iterator;

/**
 * @author xinzhixuan
 * @version 1.0
 * @date 2024/8/10 18:22
 */
@Slf4j
public class MysqlReducer extends Reducer<AnalysisKey, LongWritable, AnalysisKey, AnalysisValue> {
    @Override
    protected void setup(Reducer<AnalysisKey, LongWritable, AnalysisKey, AnalysisValue>.Context context) throws IOException, InterruptedException {
        super.setup(context);
    }

    @Override
    protected void reduce(AnalysisKey key, Iterable<LongWritable> values, Reducer<AnalysisKey, LongWritable, AnalysisKey, AnalysisValue>.Context context) throws IOException, InterruptedException {
        Iterator<LongWritable> iterator = values.iterator();
        int sumCnt = 0;
        long sumDuration = 0;
        while (iterator.hasNext()) {
            sumDuration += iterator.next().get();
            sumCnt++;
        }
        AnalysisValue value = new AnalysisValue();
        value.setSumCnt(sumCnt);
        value.setSumDuration(sumDuration);
        log.info("===reduce:key:{} --> value=>{}", key, value);
        context.write(key, value);
    }

}
